package com.jiangjiang.eshop.finance.schedule;

import com.jiangjiang.eshop.common.help.DateHelper;
import com.jiangjiang.eshop.finance.dto.PurchaseSettlementOrderDTO;
import com.jiangjiang.eshop.finance.service.PurchaseSettlementOrderService;
import com.jiangjiang.eshop.pay.service.PayService;
import com.jiangjiang.eshop.purchase.constant.SettlementPeriod;
import com.jiangjiang.eshop.purchase.dto.SupplierDTO;
import com.jiangjiang.eshop.purchase.service.SupplierService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * @ClassName MonthSettlementTask
 * @Description 月结算任务
 * @Author jhw
 * @Date 2021/9/21 5:58
 * @Version 1.0
 **/
@Slf4j
@Component
public class QuarterSettlementTask {

    @Autowired
    private PurchaseSettlementOrderService purchaseSettlementOrderService;

    @Autowired
    private SupplierService supplierService;

    @Autowired
    private PayService payService;

    @Autowired
    private DateHelper dateHelper;

    @Scheduled(cron = "0 0 0 1 1/3 ?")
    public void execute(){
        try {
            Date endDate = dateHelper.getCurrentDate();
            Date startDate = new Date(endDate.getTime() - 90 * 24 * 60 * 60 * 1000);

            List<SupplierDTO> suppliers = supplierService.queryBySettlementPeriod(SettlementPeriod.QUARTER);
            for (SupplierDTO supplier : suppliers) {

                Double totalSettlementAmount = purchaseSettlementOrderService.queryFinishedBySettlePeriod(supplier.getId(), startDate, endDate)
                        .stream()
                        .mapToDouble(PurchaseSettlementOrderDTO::getTotalSettlementAmount)
                        .sum();
                // 打款
                payService.payForSupplier(supplier.getBankName(), supplier.getBankAccount(), supplier.getBankAccountHolder(), totalSettlementAmount);
            }


        }catch (Exception e){
            log.warn("MonthSettlementTask execute error",e);
        }
    }

}
